package com.whale.cloud.util;

import com.whale.cloud.util.constant.ConstantUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** Created by maoweidong on 2017/4/20. */
public class StringUtils {
  public static String checkString(String param) {
    String value =
        null == param
                || param.equals("~!@#$%&*")
                || org.apache.commons.lang.StringUtils.isBlank(param)
            ? ""
            : param;

    String msg = "";
    value = value.replace("[", "");
    value = value.replace("]", "");
    value = value.replace("\"", "");
    String[] params = value.split(",");
    if (params.length > 1) {
      if (!Arrays.asList(params).contains("~!@#$%&*")) {
        msg = params[0];
      } else {
        for (String def : params) {
          if (!def.equals("~!@#$%&*")) {
            msg = def;
            break;
          }
        }
      }
    } else {
      msg = params[0];
    }
    if (msg.equals("~!@#$%&*")) {
      return "";
    }
    return msg;
  }

  public static boolean isNull(Object o) {
    if (o == null) {
      return true;
    }
    String to = valueOf(o);
    if (to.isEmpty() || to.equals("")) {
      return true;
    }

    return false;
  }

  public static boolean isNotNull(Object o) {
    return !isNull(o);
  }

  public static String valueOf(Object o) {
    if (o == null) {
      return "";
    }
    String ov = o.toString().trim();
    if ("null".equalsIgnoreCase(ov)) {
      return "";
    }
    return ov;
  }

  public static String valueOf(Object o, String defaultVlaue) {
    if (o == null) {
      return defaultVlaue;
    }
    String ov = o.toString().trim();
    if ("null".equalsIgnoreCase(ov)) {
      return defaultVlaue;
    }
    return ov;
  }

  public static String format_param(String param) {
    String msg = "";
    param = param.replace("[", "");
    param = param.replace("]", "");
    param = param.replace("\"", "");
    String[] params = param.split(",");
    if (params.length > 1) {
      if (!Arrays.asList(params).contains("~!@#$%&*")) {
        msg = params[0];
      } else {
        for (String def : params) {
          if (!def.equals("~!@#$%&*")) {
            msg = def;
            break;
          }
        }
      }
    } else {
      msg = params[0];
    }
    if (msg.equals("~!@#$%&*")) {
      return "";
    }
    return msg;
  }

  public static boolean isDigital(String o) {
    Pattern pattern = Pattern.compile("\\s*\\d+\\s*$");
    Matcher isNum = pattern.matcher(o);
    return isNum.find();
  }

  /**
   * 去除字符串首尾出现的某个字符.
   *
   * @param source 源字符串.
   * @param element 需要去除的字符.
   * @return String.
   */
  public static String trimFirstAndLastChar(String source, String element) {
    boolean beginIndexFlag = true;
    boolean endIndexFlag = true;
    do {
      int beginIndex = source.indexOf(element) == 0 ? 1 : 0;
      int endIndex =
          source.lastIndexOf(element) + 1 == source.length()
              ? source.lastIndexOf(element)
              : source.length();
      source = source.substring(beginIndex, endIndex);
      beginIndexFlag = (source.indexOf(element) == 0);
      endIndexFlag = (source.lastIndexOf(element) + 1 == source.length());
    } while (beginIndexFlag || endIndexFlag);
    return source;
  }

  public static String getNewString(String string) {
    string = StringUtils.trimFirstAndLastChar(string, ConstantUtil.HEAD);
    string = StringUtils.trimFirstAndLastChar(string, ConstantUtil.FISHTAIL);
    return string;
  }

  /**
   * 生成指定英文大小写随机数
   *
   * @param scope
   * @return
   */
  public static String randomNumber(int scope) {
    String randomcode = "";
    for (int i = 0; i < scope; i++) {
      //52个字母与6个大小写字母间的符号；范围为91~96
      int value = (int) (Math.random() * 58 + 65);
      while (value >= 91 && value <= 96) {
        value = (int) (Math.random() * 58 + 65);
      }
      randomcode = randomcode + (char) value;
    }
    return randomcode;
  }
  /**
   * 将对象以字符串返回
   *
   * @param obj 封装的参数对象
   * @return 返回字符串
   */
  public static String objConvertstr(Object obj) {
    if (null == obj) {
      return "";
    }
    if ((String.valueOf(obj)).equals("~!@#$%&*")) { //~!@#$%&*
      return "";
    }
    if ((String.valueOf(obj)).equals("null")) {
      return "";
    }
    if ((String.valueOf(obj)).equals("无")) {
      return "";
    }
    return !(String.valueOf(obj)).equals("") ? String.valueOf(obj) : "";
  }
  //生成指定长度字符串
  public static String getRandomString(int length){
    String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    Random random=new Random();
    StringBuffer sb=new StringBuffer();
    for(int i=0;i<length;i++){
      int number=random.nextInt(52);
      sb.append(str.charAt(number));
    }
    return sb.toString();
  }
  public static String getIpAddress(HttpServletRequest request, String defauleip) {
    String ip = request.getHeader("x-forwarded-for");
    if (StringUtils.isNull(ip) || "unknown".equalsIgnoreCase(ip) || "0:0:0:0:0:0:0:1".equalsIgnoreCase(ip)) {
      ip = request.getHeader("Proxy-Client-IP");
    }
    if (StringUtils.isNull(ip) || "unknown".equalsIgnoreCase(ip) || "0:0:0:0:0:0:0:1".equalsIgnoreCase(ip)) {
      ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (StringUtils.isNull(ip) || "unknown".equalsIgnoreCase(ip) || "0:0:0:0:0:0:0:1".equalsIgnoreCase(ip)) {
      ip = request.getHeader("HTTP_CLIENT_IP");
    }
    if (StringUtils.isNull(ip) || "unknown".equalsIgnoreCase(ip) || "0:0:0:0:0:0:0:1".equalsIgnoreCase(ip)) {
      ip = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    if (StringUtils.isNull(ip) || "unknown".equalsIgnoreCase(ip) || "0:0:0:0:0:0:0:1".equalsIgnoreCase(ip)) {
      ip = request.getRemoteAddr();
    }
    if (StringUtils.isNotNull(ip) && ip.indexOf(",") > -1) {
      String strIp = null;
      String[] ips = ip.split(",");
      int iplength = ips.length;
      for (int index = 0; index < iplength; index++) {
        strIp = ips[index];
        if (StringUtils.isNotNull(strIp) && !"unknown".equalsIgnoreCase(strIp) && !"0:0:0:0:0:0:0:1".equalsIgnoreCase(strIp)) {
          ip = strIp;
          break;
        }
      }
    }
    if (StringUtils.isNull(ip) || "unknown".equalsIgnoreCase(ip) || "0:0:0:0:0:0:0:1".equalsIgnoreCase(ip)) {
      ip = defauleip;
    }
    if (!isIp(ip)) {
      ip = "127.0.0.1";
    }

    String key = null;
    Enumeration<String> hs = request.getHeaderNames();
    while (hs.hasMoreElements()) {
      key = hs.nextElement();

    }
    return ip.equals("0:0:0:0:0:0:0:1") ? defauleip : ip;
  }


  public static boolean isIp(String ip) {
    if (StringUtils.isNull(ip)) {
      return false;
    }
    boolean isipaddress = false;

    //ip4
    Pattern pattern = Pattern.compile("^\\s*[1-9]{1,2}[\\d]?\\.[1-9]{1,2}[\\d]?\\.[1-9]{1,2}[\\d]?\\.[1-9]{1,2}[\\d]?\\s*$");
    Matcher isIp = pattern.matcher(ip);
    isipaddress = isIp.matches();
    if (isipaddress) {
      return isipaddress;
    }

    //ip6
    pattern = Pattern.compile("^\\s*[1-9]{1,2}[\\d]?\\.[1-9]{1,2}[\\d]?\\.[1-9]{1,2}[\\d]?\\.[1-9]{1,2}[\\d]?\\s*$");
    isIp = pattern.matcher(ip);

    return isIp.matches();
  }

  //是否包含中文
  public static boolean isContainChinese(String str) {

    Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
    Matcher m = p.matcher(str);
    if (m.find()) {
      return true;
    }
    return false;
  }

  //是不是数字且包含小数
  public static boolean isNumeric(String str){
    Pattern pattern = Pattern.compile("[0-9]+.?[0-9]{0,2}");
    Matcher isNum = pattern.matcher(str);
    if(!isNum.matches() ){
      return false;
    }
    return true;
  }
  //判断字符串是否符合给定的位数
  public static boolean checkLength(String str,int max,int min){
    if (str.length()<=max&&str.length()>=min){
      return false;
    }
    return true;
  }

}
